<?php

class ContentTypeService extends FServiceBase
{    
    /**
    * Get a ContentType model given its ID
    * 
    * @param int id ContentType ID
    * @return FServiceModel
    */
    public function get($params){
        $model = ContentType::model()->findByPk($this->getParam($params, 'id',0));
        if (! $model)
            $this->result->fail(ERROR_INVALID_DATA, Yii::t('Cms.ContentType','Invalid ID.'));
        $this->result->processed('model', $model);
        return $this->result;
    }
    
    public function save($params) {
        /**
        * @var CModel
        */
        $model = $this->getModel($params['ContentType'],'ContentType');
        $this->result->processed('model', $model);
        
        if (! $model->validate())
            $this->result->fail(ERROR_INVALID_DATA, Yii::t('Cms.ContentType', 'Submitted data is missing or invalid.'));
        elseif ($this->getParam($params, 'validateOnly',0) == TRUE)
            return $this->result;
        elseif (! $model->save())
            $this->result->fail(ERROR_HANDLING_DB, Yii::t('Cms.ContentType','Error while saving submitted data into database.'));
        
        return $this->result;
    }


    public function delete($params) {
        $ids = $this->getParam($params, 'ids', array());
        if ($ids <= 0) {
            return $this->result->fail(ERROR_INVALID_DATA, Yii::t('Cms.ContentType','Invalid ID.'));
        }
      
        if (!is_array($ids)) $ids = array($ids);
        foreach($ids as $id) {
            $model = ContentType::model()->findByPk($id);
            try {
                $model->delete();
            } catch (CDbException $ex) {
                $this->result->fail(ERROR_HANDLING_DB, $ex->getMessage());
            }
        }
        return $this->result;
    }
    
    /**
    * Find all content types
    * 
    * @param bool status default TRUE
    * @param bool includeCoreTypes default TRUE. Whether to include core type
    * @return FServiceModel
    */
    public function findAll($params)
    {
        $criteria = new CDbCriteria();
        $criteria->compare('status', $this->getParam($params,'status', true));
        if ($this->getParam($params, 'includeCoreTypes', true) == false)
            $criteria->addCondition("NOT (model LIKE 'Cms.models.%')");
        
        $criteria->order = 'name';
        $models = ContentType::model()->findAll($criteria);
        $this->result->processed('data', $models);
        
        return $this->result;
    }
    
    public function changeStatus($params)
    {
        $id = $this->getParam($params, 'ids', array());
        $status = (boolean) $this->getParam($params, 'value', false);
        if (! is_array($id))
        {
            $id = array($id);
        }
        ContentType::model()->updateByPk($id, array('status'=>$status));
        return $this->result;
    }
}